package com.csmy.my.center.action;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.csmy.my.center.dao.IReader;
import com.csmy.my.center.filter.AuthorizationInterceptor;
import com.csmy.my.center.module.UserInfo;
import com.csmy.my.center.service.UserInfoService;
import com.csmy.my.center.util.CTConstants;
import com.csmy.my.center.util.CTUtils;
import com.csmy.my.center.util.PageModel;
import com.csmy.my.center.util.RequestUtil;
import com.csmy.my.center.util.SpringBeanLoader;
import com.csmy.my.center.util.StringUtil;
import com.csmy.my.center.util.ZHToEN;
import com.csmy.my.center.util.dataconvert.Dto;
import com.csmy.my.center.util.dataconvert.impl.BaseDto;
import com.csmy.my.center.util.dataconvert.json.JsonHelper;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
@Controller
/**
 * 基本Action接口
 * 
 * @author wgp
 * @since 2013-01-15
 * 
 */
@SuppressWarnings("unchecked")
public abstract class BaseActionSupport extends ActionSupport implements Preparable {
	protected Logger logger = Logger.getLogger(getClass());
	
	public static int start=0;
	public static Integer pageNo=1;
	public static int pageSize=20;
	
	public PageModel pager = new PageModel();
	
	UserInfo userInfo = null;
	/**
	 * Action基类中给子类暴露的一个DAO接口<br>
	 * <b>只能在Action子类中使用此Dao接口进行非事物相关的操作</b>:仅能进行查询操作
	 */
	protected IReader CTReader = (IReader) getService("CTReader");
	/**
	 * 从服务容器中获取服务组件
	 * 
	 * @param pBeanName
	 *            :BeanID
	 * @return Object
	 */
	protected Object getService(String pBeanId) {
		
	//	com.mysql.jdbc.Driver
		Object springBean = SpringBeanLoader.getSpringBean(pBeanId);
		return springBean;
	}
	/**
	 * 预设一些变量，便于调用
	 */
	public void prepare() throws Exception {
		userInfo = getUser(ServletActionContext.getRequest());
	}

	/**
	 * 将ISO8859_1编码的字符串转化为UTF-8编码的字符串 主要用来处理中文显示乱码的问题
	 * 
	 * @param ISO8859_1str
	 *            通过ISO8859_1编码的字符串
	 * @return 通过UTF-8编码的字符串
	 * @throws UnsupportedEncodingException
	 */
	protected String CharsetFilter(String keys)
			throws UnsupportedEncodingException {
		// 将参数UTF-8编码
		String value1 = keys;
		value1 = new String(value1.getBytes("ISO8859-1"), "UTF-8");
		System.out.println("utf-8==" + value1);
		return value1;
	}

	/**
	 * 打印参数方法
	 */
	protected void print() throws UnsupportedEncodingException {
		for (Object key : $map().keySet()) {
			try {
				String str[] = (String[]) $map().get(key);
				for (int i = 0; i < str.length; i++) {
					System.out.println(str[i]);
				}
			} catch (Exception e) {
				System.out.println(key + "==" + $map().get(key));
			}
		}

	}

	/**
	 * 转换用户对象为dto
	 * @param userInfo
	 * @return
	 */
	public static Map beanToMap(Object bean) {
		if (bean == null) return new HashMap();
		Map rst = new HashMap();
		if (bean instanceof java.util.Map) {
			rst = (Map) bean;
		} else if (bean instanceof String || bean instanceof Long || bean instanceof Integer) {
			rst.put("value", bean);
		} else {
			try {
				rst.putAll(PropertyUtils.describe(bean));
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			}
		}
		return rst;
	}
	
	
	
	/**
	 * 获取指定字典参数集合
	 * @param code_name
	 * @return
	 */
	protected List<Dto> getCodeList(String code_name) {
		
		List<Dto> rList = null;
		List<Dto> rList2 = null;
		Dto codeDto = (BaseDto)getContextAtrribute(CTConstants.CT_CODE_LIST);
		List<Dto> cList = codeDto.getAsList(code_name);
		if(CTUtils.isNotEmpty(cList)){
			Dto reDto = null;
			rList = new ArrayList<Dto>();
			for (int i=0;i<cList.size();i++) {
				reDto = (BaseDto)cList.get(i);
				if(!"-9".equals(reDto.getAsString("code"))){
					rList.add(reDto);
				}
			}
			
			//排序
			rList2 = StringUtil.sortDtoList(rList, "sort_no", "asc");
		}
		return rList2;
	}
	
	/**
	 * 根据值获取字典描述
	 * @param coList
	 * @param value
	 * @return
	 */
	protected String getCodeName(List<Dto> coList,String value) {
		String retStr = "";
		if(CTUtils.isNotEmpty(coList)){
			for (Dto dto : coList) {
				if(value.equals(dto.getAsString("code"))){
					retStr = dto.getAsString("code_desc");
					break;
				}
			}
		}
		return retStr;
	}
	
	/**
	 * 根据值获取字典描述
	 * @param coList
	 * @param code_value
	 * @return
	 */
	protected String getCodeName(String field_code,String code_value) {
		String retStr = "";
		List<Dto> coList = getCodeList(field_code);
		if(CTUtils.isNotEmpty(coList)){
			for (Dto dto : coList) {
				if(code_value.equals(dto.getAsString("code_value"))){
					retStr = dto.getAsString("code_desc");
					break;
				}
			}
		}
		return retStr;
	}
	
	/**
	 * 根据菜系获取名称
	 * @param coList
	 * @param code_value
	 * @return
	 */
	protected String getDepartName(String depart_id) {
		String retStr = "";
		List<Dto> coList = (List<Dto>)getContextAtrribute(CTConstants.CT_DEPART_LIST);
		if(CTUtils.isNotEmpty(coList)){
			for (Dto dto : coList) {
				if(depart_id.equals(dto.getAsString("depart_id"))){
					retStr = dto.getAsString("depart_name");
					break;
				}
			}
		}
		return retStr;
	}
	
	/**
	 * 根据菜系获取编码
	 * @param coList
	 * @param code_value
	 * @return
	 */
	protected String getDepartCode(String depart_id) {
		String retStr = "";
		List<Dto> coList = (List<Dto>)getContextAtrribute(CTConstants.CT_DEPART_LIST);
		if(CTUtils.isNotEmpty(coList)){
			for (Dto dto : coList) {
				if(depart_id.equals(dto.getAsString("depart_id"))){
					retStr = dto.getAsString("depart_code");
					break;
				}
			}
		}
		return retStr;
	}
	
	/**
	 * 根据菜系获取编码
	 * @param coList
	 * @param code_value
	 * @return
	 */
	protected String getDepartNameByCode(String depart_code) {
		String retStr = "";
		List<Dto> coList = (List<Dto>)getContextAtrribute(CTConstants.CT_DEPART_LIST);
		if(CTUtils.isNotEmpty(coList)){
			for (Dto dto : coList) {
				if(depart_code.equals(dto.getAsString("depart_code"))){
					retStr = dto.getAsString("depart_name");
					break;
				}
			}
		}
		return retStr;
	}
	
	/**
	 * 根据值获取字典描述
	 * @param coList
	 * @param code_desc
	 * @return
	 */
	protected String getCodeValue(String field_code,String code_desc) {
		String retStr = "";
		List<Dto> coList = getCodeList(field_code);
		if(CTUtils.isNotEmpty(coList)){
			for (Dto dto : coList) {
				if(code_desc.equals(dto.getAsString("code_desc"))){
					retStr = dto.getAsString("code_value");
					break;
				}
			}
		}
		return retStr;
	}
	
	
	/**
	 * 根据描述获取字典值
	 * @param coList
	 * @param name
	 * @return
	 */
	protected String getCodeValue(List<Dto> coList,String code_desc) {
		String retStr = "";
		if(CTUtils.isNotEmpty(coList)){
			for (Dto dto : coList) {
				if(code_desc.equals(dto.getAsString("code_desc"))){
					retStr = dto.getAsString("code_value");
					break;
				}
			}
		}
		return retStr;
	}
	
	/**
	 * 将指定的字典参数集合转换为json数据格式
	 * @param code_name
	 * @return
	 */
	protected String getCodeJsonData(String code_name) {
		String jsonString = "";
		try {
			int count = 0;
			List<Dto> codeList = getCodeList(code_name);
			StringBuffer sbBuffer = new StringBuffer("");
			if(CTUtils.isNotEmpty(codeList)){
				sbBuffer.append("{\"treeNodes\":[");
				for (Dto dto : codeList) {
					count++;
					sbBuffer.append("{");
					sbBuffer.append("\"id\":\"").append(dto.getAsString("code_value")).append("\",");
					sbBuffer.append("\"name\":\"").append(dto.getAsString("code_desc")).append("\",");
					sbBuffer.append("\"open\":\"").append("true").append("\",");
					sbBuffer.append("\"parentId\":\"").append("").append("\"");
					sbBuffer.append("}");
					if(count<codeList.size()){
						sbBuffer.append(",");
					}
				}
				sbBuffer.append("]}");
			}
			jsonString = sbBuffer.toString();
			StringUtil.xprint("jsonData="+jsonString);
		}catch (Exception e) {
				e.printStackTrace();
		}
		return jsonString;
	}
	
	
	/**
	 * 将指定的字典参数集合转换为json数据格式（一般下拉）
	 * @param code_name
	 * @return
	 */
	protected String getCombJsonData(String code_name) {
		String jsonString = "";
		try {
			int count = 0;
			List<Dto> codeList = getCodeList(code_name);
			StringBuffer sbBuffer = new StringBuffer("");
			if(CTUtils.isNotEmpty(codeList)){
				sbBuffer.append("{\"list\":[");
				for (Dto dto : codeList) {
					count++;
					sbBuffer.append("{");
					sbBuffer.append("\"value\":\"").append(dto.getAsString("code_value")).append("\",");
					sbBuffer.append("\"key\":\"").append(dto.getAsString("code_desc")).append("\"");
					sbBuffer.append("}");
					if(count<codeList.size()){
						sbBuffer.append(",");
					}
				}
				sbBuffer.append("]}");
			}
			jsonString = sbBuffer.toString();
			StringUtil.xprint("jsonData="+jsonString);
		}catch (Exception e) {
				e.printStackTrace();
		}
		return jsonString;
	}
	
	
	/**
	 * 获取字符过滤器json数据
	 * @param space_name
	 * @return
	 */
	protected String getFilterJsonData(String space_name,List<Dto> exList) {
		String jsonString = "";
		try {
			int count = 0;
			List<Dto> roleList = CTReader.queryForList(space_name);
			StringBuffer sbBuffer = new StringBuffer("");
			if(CTUtils.isNotEmpty(roleList)){
				sbBuffer.append("{\"list\":[");
				for (Dto dto : roleList) {
					count++;
					if(StringUtil.checkListExist(exList, "role_code", dto.getAsString("role_code"))){
						continue;
					}
					sbBuffer.append("{");
					sbBuffer.append("\"value\":\"").append(dto.getAsString("role_code")).append("\",");
					sbBuffer.append("\"key\":\"").append(dto.getAsString("role_name")).append("\"");
					sbBuffer.append("}");
					if(count<roleList.size()){
						sbBuffer.append(",");
					}
				}
				sbBuffer.append("]}");
			}
			jsonString = sbBuffer.toString();
			StringUtil.xprint("jsonData="+jsonString);
		}catch (Exception e) {
				e.printStackTrace();
		}
		return jsonString;
	}
	
	
	/**
	 * 获取字符过滤器json数据(通用)
	 * @param space_name
	 * @return
	 */
	protected String getComFilterJsonData(List<Dto> cList,String pro_code,String pro_name) {
		String jsonString = "";
		try {
			int count = 0;
			StringBuffer sbBuffer = new StringBuffer("");
			if(CTUtils.isNotEmpty(cList)){
				sbBuffer.append("{\"list\":[");
				for (Dto dto : cList) {
					count++;
					sbBuffer.append("{");
					sbBuffer.append("\"value\":\"").append(dto.getAsString(pro_code)).append("\",");
					sbBuffer.append("\"key\":\"").append(dto.getAsString(pro_name)).append("\"");
					sbBuffer.append("}");
					if(count<cList.size()){
						sbBuffer.append(",");
					}
				}
				sbBuffer.append("]}");
			}
			jsonString = sbBuffer.toString();
			StringUtil.xprint("jsonData="+jsonString);
		}catch (Exception e) {
				e.printStackTrace();
		}
		return jsonString;
	}
	
	/**
	 * 获取中文的拼音
	 * @param zh_name
	 * @param allWord
	 * @param upCase
	 * @return
	 */
	protected String getPinYin(String zh_name,boolean allWord,boolean upCase) {
		String reStr = "";
		try {
			 if(CTUtils.isNotEmpty(zh_name)){
				 if(allWord){
					 reStr = new ZHToEN().getPingyin(zh_name);
				 }else{
					 reStr = new ZHToEN().converterToFirstSpell(zh_name);
				 }
				 
				 if(upCase){
					 reStr = reStr.toUpperCase();
				 }else{
					 reStr = reStr.toLowerCase();
				 }
			 }
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return reStr;
	}
	
	/**
	 * 将菜单功能json数据格式（一般下拉）
	 * @param menu_code
	 * @return
	 */
	protected String getMenuFuncJsonData(String menu_code) {
		String jsonString = "";
		try {
			int count = 0;
			String menu_name = "";
			Dto inDto = new BaseDto();
			inDto.put("menu_code", menu_code);
			List<Dto> codeList = CTReader.queryForList("resource.getMenuFunctions", inDto);
			StringBuffer sbBuffer = new StringBuffer("");
			if(CTUtils.isNotEmpty(codeList)){
				sbBuffer.append("{\"list\":[");
				for (Dto dto : codeList) {
					count++;
					sbBuffer.append("{");
					sbBuffer.append("\"value\":\"").append(dto.getAsString("permit_code")).append("\",");
					if(CTUtils.isEmpty(dto.getAsString("action_code"))){
						sbBuffer.append("\"key\":\"").append("访问").append("\"");
					}else{
						menu_name = dto.getAsString("permit_desc");
						if(menu_name.indexOf("_")>0){
							menu_name = menu_name.substring(menu_name.indexOf("_")+1, menu_name.length());
						}
					   sbBuffer.append("\"key\":\"").append(menu_name).append("\"");
					}
					sbBuffer.append("}");
					if(count<codeList.size()){
						sbBuffer.append(",");
					}
				}
				sbBuffer.append("]}");
			}
			jsonString = sbBuffer.toString();
			StringUtil.xprint("jsonData="+jsonString);
		}catch (Exception e) {
				e.printStackTrace();
		}
		return jsonString;
	}
	
	
	/**
	 * 获取树结构数据
	 * @param codeList 结果集合
	 * @param code_id 对应id字段
	 * @param code_name 对应text字段
	 * @param parent_code 上级字段 没有上级用 0代替
	 * @return
	 */
	protected String getFuncTreeJsonData(List<Dto> codeList ,String code_id,
			String code_name,String parent_code,HttpServletRequest request ) {
		String jsonString = "";
		try {
			int count = 0;
			StringBuffer sbBuffer = new StringBuffer("");
			if(CTUtils.isNotEmpty(codeList)){
				String p_code = "";
				String ckd = "";
				for (Dto dto : codeList) {
					count++;
					p_code = dto.getAsString(parent_code);
					ckd = dto.getAsString("chkDisabled");
					sbBuffer.append("{");
					sbBuffer.append("\"id\":\"").append(dto.getAsString(code_id)).append("\",");
					sbBuffer.append("\"name\":\"").append(dto.getAsString(code_name)).append("\",");
					sbBuffer.append("\"chkDisabled\":\"").append(ckd).append("\",");
					if(codeList.size()==1){
					   sbBuffer.append("\"isParent\":\"").append("false").append("\",");
					}else{
					   sbBuffer.append("\"isParent\":\"").append(dto.getAsString("isParent")).append("\",");
					}
					
					if("0".equals(p_code)){
					   sbBuffer.append("\"open\":\"").append("true").append("\",");
			    	}else{
			    	   sbBuffer.append("\"open\":\"").append("false").append("\",");
			    	}
					
					if(CTUtils.isEmpty(parent_code)){
						parent_code = "0";
					}
					sbBuffer.append("\"pId\":\"").append(p_code).append("\",");
					sbBuffer.append("\"checked\":\"").append(dto.getAsString("checked")).append("\"");
					sbBuffer.append("}");
					if(count<codeList.size()){
						sbBuffer.append(",");
					}
				}
			}
			jsonString = sbBuffer.toString();
			StringUtil.xprint("treejsonData="+jsonString);
		}catch (Exception e) {
				e.printStackTrace();
		}
		return jsonString;
	}
	
	/**
	 * 将指定的参数集合转换为json数据格式（下拉使用）
	 * @param codeList 结果集合
	 * @param code_id 对应id字段
	 * @param code_name 对应text字段
	 * @param parent_code 上级字段 没有上级用 0代替
	 * @return
	 */
	protected String getcCommJsonData(List<Dto> codeList ,String code_id,String code_name,String parent_code,String isOpen) {
		String jsonString = "";
		try {
			int count = 0;
			StringBuffer sbBuffer = new StringBuffer("");
			if(CTUtils.isNotEmpty(codeList)){
				if("menu_code".equals(code_id)){
				   sbBuffer.append("{\"treeNodes\":[{\"id\":\"01\",\"name\":\"资源管理\",\"parentId\":\"0\",\"clickExpand\":\"true\"},");
				}else if("code_id".equals(code_id)){
				   sbBuffer.append("{\"treeNodes\":[{\"id\":\"0\",\"name\":\"系统参数\",\"parentId\":\"-1\"},");
				}else{
				   sbBuffer.append("{\"treeNodes\":[");
				}
				String p_code = "";
				for (Dto dto : codeList) {
					count++;
					p_code = dto.getAsString(parent_code);
					sbBuffer.append("{");
					sbBuffer.append("\"id\":\"").append(dto.getAsString(code_id)).append("\",");
					sbBuffer.append("\"name\":\"").append(dto.getAsString(code_name)).append("\",");
					if("0".equals(dto.getAsString("leaf"))){
					   sbBuffer.append("\"nocheck\":\"").append("true").append("\",");
					}
					sbBuffer.append("\"open\":\"").append(isOpen).append("\",");
					if(CTUtils.isEmpty(parent_code)){
						parent_code = "0";
					}
					sbBuffer.append("\"parentId\":\"").append(p_code).append("\"");
					sbBuffer.append("}");
					if(count<codeList.size()){
						sbBuffer.append(",");
					}
				}
				sbBuffer.append("]}");
			}
			jsonString = sbBuffer.toString();
			StringUtil.xprint("jsonData="+jsonString);
		}catch (Exception e) {
				e.printStackTrace();
		}
		return jsonString;
	}
	
	
	/**
	 * 获取菜单树结构数据
	 * @param codeList
	 * @param code_id
	 * @param code_name
	 * @param parent_code
	 * @param url
	 * @param target
	 * @return
	 */
	protected String getMenuTreeJsonData(List<Dto> codeList ,String code_id,
			String code_name,String parent_code,String url,String target,
			HttpServletRequest request) {
		String jsonString = "";
		try {
			int count = 0;
			String path = request.getContextPath();
			StringBuffer sbBuffer = new StringBuffer("");
			if(CTUtils.isNotEmpty(codeList)){
				
				String p_code = "";
				//sbBuffer.append("{id:\"01\",name:\"系统资源\",open:true,pId:-1,icon:\""+path+"/images/base.gif\"},");
				for (Dto dto : codeList) {
					count++;
					p_code = dto.getAsString(parent_code);
					sbBuffer.append("{");
					sbBuffer.append("id:\"").append(dto.getAsString(code_id)).append("\",");
					sbBuffer.append("name:\"").append(dto.getAsString(code_name)).append("\",");
					if("1".equals(dto.getAsString("expanded"))){
					   sbBuffer.append("open:").append("true").append(",");
			    	}else{
			    	   sbBuffer.append("open:").append("false").append(",");
			    	}
					
					if(CTUtils.isEmpty(parent_code)){
						parent_code = "0";
					}
					sbBuffer.append("pId:\"").append(p_code).append("\",");
					sbBuffer.append("url:\"").append(dto.getAsString(url)).append("\",");
					sbBuffer.append("target:\"").append(target).append("\"");
					sbBuffer.append("}");
					if(count<codeList.size()){
						sbBuffer.append(",");
					}
				}
			}
			jsonString = sbBuffer.toString();
			StringUtil.xprint("treejsonData="+jsonString);
		}catch (Exception e) {
				e.printStackTrace();
		}
		return jsonString;
	}
	
	/**
	 * 将指定的参数集合转换为json数据格式（下拉使用）
	 * @param codeList 结果集合
	 * @param code_id 对应id字段
	 * @param code_name 对应text字段
	 * @param parent_code 上级字段 没有上级用 0代替
	 * @return
	 */
	protected String getcCommJsonData(List<Dto> codeList ,String code_id,String code_name,
			String parent_code,String isOpen,boolean containRoot, String root_name,boolean clickExpand) {
		String jsonString = "";
		try {
			int count = 0;
			StringBuffer sbBuffer = new StringBuffer("");
			if(CTUtils.isNotEmpty(codeList)){
				if(containRoot){
					if(clickExpand){
				      sbBuffer.append("{\"treeNodes\":[{\"id\":\"01\",\"clickExpand\":\"true\",\"name\":\""+root_name+"\",\"parentId\":\"0\"},");
					}else{
					  sbBuffer.append("{\"treeNodes\":[{\"id\":\"01\",\"name\":\""+root_name+"\",\"parentId\":\"0\"},");
					}
				}else{
				   sbBuffer.append("{\"treeNodes\":[");
				}
				String p_code = "";
				for (Dto dto : codeList) {
					count++;
					p_code = dto.getAsString(parent_code);
					sbBuffer.append("{");
					sbBuffer.append("\"id\":\"").append(dto.getAsString(code_id)).append("\",");
					sbBuffer.append("\"name\":\"").append(dto.getAsString(code_name)).append("\",");
					if("0".equals(dto.getAsString("leaf"))){
					   sbBuffer.append("\"nocheck\":\"").append("true").append("\",");
					   if(clickExpand){
					      sbBuffer.append("\"clickExpand\":\"").append("true").append("\",");
					   }
					}
					sbBuffer.append("\"open\":\"").append(isOpen).append("\",");
					if(CTUtils.isEmpty(parent_code)){
						parent_code = "0";
					}
					sbBuffer.append("\"parentId\":\"").append(p_code).append("\"");
					sbBuffer.append("}");
					if(count<codeList.size()){
						sbBuffer.append(",");
					}
				}
				sbBuffer.append("]}");
			}
			jsonString = sbBuffer.toString();
			StringUtil.xprint("jsonData="+jsonString);
		}catch (Exception e) {
				e.printStackTrace();
		}
		return jsonString;
	}
	
	/**
	 * 获取左右下拉树数据
	 * @param codeList 结果集合
	 * @param code_id 对应id字段
	 * @param code_name 对应text字段
	 * @param parent_code 上级字段 没有上级用 0代替
	 * @return
	 */
	protected String getListerTreeJsonData(List<Dto> codeList ,String code_id,String code_name,String parent_code ) {
		String jsonString = "";
		try {
			int count = 0;
			StringBuffer sbBuffer = new StringBuffer("");
			if(CTUtils.isNotEmpty(codeList)){
				
				sbBuffer.append("{\"toList\":[],\"fromList\":[");
				String p_code = "";
				for (Dto dto : codeList) {
					count++;
					p_code = dto.getAsString(parent_code);
					sbBuffer.append("{");
					sbBuffer.append("\"id\":\"").append(dto.getAsString(code_id)).append("\",");
					sbBuffer.append("\"name\":\"").append(dto.getAsString(code_name)).append("\",");
					sbBuffer.append("\"drag\":\"").append("true").append("\",");
					if("0".equals(p_code)){
					   sbBuffer.append("\"open\":\"").append("true").append("\",");
			    	}else{
			    	   sbBuffer.append("\"open\":\"").append("false").append("\",");
			    	}
					
					if(CTUtils.isEmpty(parent_code)){
						parent_code = "0";
					}
					sbBuffer.append("\"parentId\":\"").append(p_code).append("\",");
					sbBuffer.append("\"oldParentId\":\"").append(p_code).append("\"");
					sbBuffer.append("}");
					if(count<codeList.size()){
						sbBuffer.append(",");
					}
				}
				sbBuffer.append("]}");
			}
			jsonString = sbBuffer.toString();
			StringUtil.xprint("ListerTreejsonData="+jsonString);
		}catch (Exception e) {
				e.printStackTrace();
		}
		return jsonString;
	}
	
	
	/**
	 * 获取通用树结构数据
	 * @param cList
	 * @param var_id
	 * @param var_name
	 * @param parent_id
	 * @param url
	 * @param target
	 * @param roo_name
	 * @param containRoot
	 * @param request
	 * @return
	 */
	protected String getCommZTreeJsonData(List<Dto> cList ,String var_id,String var_name,
			String parent_id,String url,String target,String roo_name,boolean containRoot,HttpServletRequest request) {
		String jsonString = "";
		try {
			int count = 0;
			String path = request.getContextPath();
			StringBuffer sbBuffer = new StringBuffer("");
			if(CTUtils.isNotEmpty(cList)){
				
				String p_code = "";
				if(containRoot){
				   sbBuffer.append("{id:\"0\",name:\""+roo_name+"\",open:true,pId:-1,icon:\""+path+"/images/base.gif\"},");
				}
				for (Dto dto : cList) {
					count++;
					p_code = dto.getAsString(parent_id);
					sbBuffer.append("{");
					sbBuffer.append("id:\"").append(dto.getAsString(var_id)).append("\",");
					sbBuffer.append("name:\"").append(dto.getAsString(var_name)).append("\",");
					if("01".equals(p_code)){
					   sbBuffer.append("open:").append("true").append(",");
			    	}else{
			    	   sbBuffer.append("open:").append("false").append(",");
			    	}
					
					if(CTUtils.isEmpty(p_code)){
						p_code = "0";
					}
					sbBuffer.append("pId:\"").append(p_code).append("\",");
					sbBuffer.append("url:\"").append(url+"&"+var_id+"="+dto.getAsString(var_id)).append("\",");
					sbBuffer.append("target:\"").append(target).append("\"");
					sbBuffer.append("}");
					if(count<cList.size()){
						sbBuffer.append(",");
					}
				}
			}
			jsonString = sbBuffer.toString();
			StringUtil.xprint("treejsonData="+jsonString);
		}catch (Exception e) {
				e.printStackTrace();
		}
		return jsonString;
	}
	
	
	
	/**
	 * 获取全局参数
	 * @param attr_name
	 * @return
	 */
	protected Object getContextAtrribute(String attr_name) {
		return ServletActionContext.getServletContext().getAttribute(attr_name);
	}
	
	/**
	 * 设置全局参数
	 * @param attr_name
	 * @param object
	 */
	protected void setContextAtrribute(String attr_name,Object object) {
	    ServletActionContext.getServletContext().setAttribute(attr_name, object);
	}

	/**
	 * 直接获取参数
	 */
	protected String $(String name) {
		return ServletActionContext.getRequest().getParameter(name);
	}

	/**
	 * 获取request所有的参数
	 * 
	 * @throws UnsupportedEncodingException
	 */
	protected Map $map() {
		return RequestUtil.getMap(ServletActionContext.getRequest());
	}

	protected Long $long(String name) {
		String v = $(name);
		return v == null ? null : Long.parseLong(v);
	}

	protected Integer $int(String name) {
		String v = $(name);
		return v == null ? null : Integer.parseInt(v);
	}

	protected Boolean $bool(String name) {
		String v = $(name);
		return v == null ? null : Boolean.parseBoolean(v);
	}
	
	/**
	 * 获取全局数据对象
	 * @return
	 */
	protected Dto getContextDto() {
		return (BaseDto)ServletActionContext.getServletContext().getAttribute(CTConstants.USER_PERMIT_LIST);
	}
	
	/**
	 * 获取上下文中全局变量
	 * @param name 标识符
	 * @return
	 */
	protected Dto getContextProperty(String name) {
		return (BaseDto)getContextDto().get(name);
	}
	

	/**
	 * 获取一个Session属性对象
	 * 
	 * @param request
	 * @param sessionName
	 * @return
	 */
	protected Object getSessionAttribute(String sessionKey) {
		Object objSessionAttribute = null;
		HttpSession session = ServletActionContext.getRequest().getSession(
				false);
		if (session != null) {
			objSessionAttribute = session.getAttribute(sessionKey);
		}
		return objSessionAttribute;
	}

	/**
	 * 设置一个Session属性对象
	 * 
	 * @param request
	 * @param sessionName
	 * @return
	 */
	protected void setSessionAttribute(String sessionKey,
			Object objSessionAttribute) {
		HttpSession session = ServletActionContext.getRequest().getSession();
		if (session != null)
			session.setAttribute(sessionKey, objSessionAttribute);
	}

	/**
	 * 移除Session对象属性值
	 * 
	 * @param request
	 * @param sessionName
	 * @return
	 */
	protected void removeSessionAttribute(String sessionKey) {
		HttpSession session = ServletActionContext.getRequest().getSession();
		if (session != null)
			session.removeAttribute(sessionKey);
	}

	/**
	 * 获取session
	 * 
	 * @param request
	 * @return
	 */
	protected HttpSession getCRSession(HttpServletRequest request) {
		return request.getSession();
	}

	/**
	 * 快速获取session中当前用户信息
	 * 
	 * @param request
	 * @return
	 */
	protected UserInfo getUser(HttpServletRequest request) {
		
		UserInfo ui=	(UserInfo) getCRSession(ServletActionContext.getRequest())
		.getAttribute(CTConstants.SESSION_USER);
		if(ui==null)
		
			ui=	new AuthorizationInterceptor().getCurUserInfo(request, userInfoService);
		return ui;
				
	}
	@Autowired
	private UserInfoService userInfoService;
	
	/**
	 * 将请求参数封装为Dto
	 * 
	 * @param request
	 * @return
	 */
	public static Dto getPraramAsDto(HttpServletRequest request) {
		Dto dto = new BaseDto();
		Map map = request.getParameterMap();
		Iterator keyIterator = (Iterator) map.keySet().iterator();
		while (keyIterator.hasNext()) {
			String key = (String) keyIterator.next();
			String value = ((String[]) (map.get(key)))[0];
			dto.put(key, value.trim());
		}
		StringUtil.xprint("打印参数："+dto);
		return dto;
	}

	/**
	 * 将请求参数封装为Dto
	 * 
	 * @param request
	 * @return
	 */
	public static Dto getPraramsAsDto(HttpServletRequest request) {
		Dto dto = new BaseDto();
		Map map = request.getParameterMap();
		Iterator keyIterator = (Iterator) map.keySet().iterator();
		while (keyIterator.hasNext()) {
			String key = (String) keyIterator.next();
			String value = ((String[]) (map.get(key)))[0];
			

			//处理字符编码  ati q213 recomm beir garab char
//			StringUtil.xprint("value=="+value);
//			String ccode = getParamValue("USE_UTF8_CODE");
//			if(CTUtils.isNotEmpty(ccode)){
//				StringUtil.xprint("使用UTF8编码过滤");
//				try {
//					value = new String(value.getBytes("ISO8859-1"), "UTF-8");
//					value=java.net.URLDecoder.decode(value,"utf-8"); 
//				} catch (UnsupportedEncodingException e) {
//					e.printStackTrace();
//				}
//			}
			dto.put(key, value.trim());
		}
		StringUtil.xprint("打印参数："+dto);
		return dto;
	}
	
	
	/**
	 * 将请求参数封装为Dto
	 * POST 提交方式
	 * @param request
	 * @return
	 */
	public static Dto getFormPraramsAsDto(HttpServletRequest request) {
		Dto dto = new BaseDto();
		DiskFileItemFactory factory = new DiskFileItemFactory(); 
		ServletFileUpload upload = new ServletFileUpload(factory); 
		List items;
		try {
			items = upload.parseRequest(request);
			for(Object object:items){ 
			    FileItem fileItem = (FileItem) object; 
			    if (fileItem.isFormField()) { 
			    	StringUtil.xprint("getFieldName："+fileItem.getFieldName());
			    	dto.put(fileItem.getFieldName(), fileItem.getString("utf-8"));//如果你页面编码是utf-8的 
			    } 
			} 
			StringUtil.xprint("打印带上传表单参数："+dto);
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		return dto;
	}
	

	/**
	 * 获取全局参数值
	 * 
	 * @param pParamKey
	 *            参数键名
	 * @return
	 */
	public static String getParamValue(String pParamKey,
			HttpServletRequest request) {
		String paramValue = "";
		ServletContext context = request.getSession().getServletContext();
		if (CTUtils.isEmpty(context)) {
			return "";
		}
		List paramList = (List) context.getAttribute("EAPARAMLIST");
		for (int i = 0; i < paramList.size(); i++) {
			Dto paramDto = (BaseDto) paramList.get(i);
			if (pParamKey.equals(paramDto.getAsString("paramkey"))) {
				paramValue = paramDto.getAsString("paramvalue");
			}
		}
		return paramValue;
	}
	
	/**
	 * 获取全局参数
	 * @param param_key
	 * @return
	 */
	public static String getParamValue(String param_key) {
		String param_value=null;
		Dto paramDto = (BaseDto)ServletActionContext.getServletContext().getAttribute(CTConstants.CT_PARAM_LIST);
		if(CTUtils.isNotEmpty(paramDto)){
			Dto perDto = (BaseDto)paramDto.get(param_key);
			if(CTUtils.isNotEmpty(perDto)){
				param_value = perDto.getAsString("param_value");
			}
		}
		return param_value;
	}
	
	/**
	 * 通用打印方法 必须指定类型
	 */
	protected static void printObj(String type, Object obj) {
		if (type.equals("String")) {
			System.out.println(obj.toString());
		}
		if (type.equals("List")) {
			List list = (ArrayList) obj;
			Iterator it = list.iterator();
			while (it.hasNext()) {
				System.out.println(it.next());
			}
		}
		if (type.equals("Set")) {
			Set kset = (HashSet) obj;
			Iterator it = kset.iterator();
			while (it.hasNext()) {
				System.out.println(it.next());
			}
		}
		if (type.equals("Array")) {
			String[] arr = (String[]) obj;
			for (int i = 0; i < arr.length; i++) {
				System.out.println(arr[i]);
			}
		}
		if (type.equals("Boolean")) {
			System.out.println(obj);
		}
		if (type.equals("Map")) {
			Map kmap = (HashMap) obj;
			Set key = kmap.keySet();
			Set entry = kmap.entrySet();

			Iterator itv = entry.iterator();
			while (itv.hasNext()) {
				System.out.println(String.valueOf(itv.next()));
			}

		}
	}

	/**
	 * 字符转码
	 * 
	 * @param str
	 * @return
	 */
	protected static String CCharseter(String str, String set) {
		try {
			if (str != null && !"".equals(str)) {
				return new String(str.getBytes("ISO8859-1"), set);
			}
		} catch (Exception e) {
			e.printStackTrace(); // 输出堆栈信息
		}
		return null;
	}

	/**
	 * 输出响应
	 * 
	 * @param str
	 * @throws IOException
	 */
	protected void write(String str, HttpServletResponse response)
			throws IOException {
		response.getWriter().write(str);
		response.getWriter().flush();
		response.getWriter().close();
	}

	/**
	 * 直接将List转为分页所需要的Json资料格式
	 * 
	 * @param list
	 *            需要编码的List对象
	 * @param totalCount
	 *            记录总数
	 * @param pDataFormat
	 *            时间日期格式化,传null则表明List不包含日期时间属性
	 */
	protected String encodeList2PageJson(List list, Integer totalCount,
			String dataFormat) {
		return JsonHelper.encodeList2PageJson(list, totalCount, dataFormat);
	}

	/**
	 * 将数据系列化为表单数据填充所需的Json格式
	 * 
	 * @param pObject
	 *            待系列化的对象
	 * @param pFormatString
	 *            日期时间格式化,如果为null则认为没有日期时间型字段
	 * @return
	 */
	protected String encodeDto2FormLoadJson(Dto pDto, String pFormatString) {
		return JsonHelper.encodeDto2FormLoadJson(pDto, pFormatString);
	}

	/**
	 * 将数据系列化为Json格式
	 * 
	 * @param pObject
	 *            待系列化的对象
	 * @param pFormatString
	 *            日期时间格式化,如果为null则认为没有日期时间型字段
	 * @return
	 */
	protected String encodeObject2Json(Object pObject, String pFormatString) {
		return JsonHelper.encodeObject2Json(pObject, pFormatString);
	}

	/**
	 * 将数据系列化为Json格式
	 * 
	 * @param pObject
	 *            待系列化的对象
	 * @return
	 */
	protected String encodeObjectJson(Object pObject) {
		return JsonHelper.encodeObject2Json(pObject);
	}

	/**
	 * 
	 * 交易成功提示信息
	 * 
	 * @param pMsg
	 *            提示信息
	 * @param pResponse
	 * @return
	 * @throws IOException
	 */
	protected void setOkTipMsg(String pMsg, HttpServletResponse response)
			throws IOException {
		Dto outDto = new BaseDto(CTConstants.TRUE, pMsg);
		write(outDto.toJson(), response);
	}

	/**
	 * 
	 * 交易失败提示信息(特指：业务交易失败并不是请求失败)<br>
	 * 和Form的submit中的failur回调对应,Ajax.request中的failur回调是值请求失败
	 * 
	 * @param pMsg
	 *            提示信息
	 * @param pResponse
	 * @return
	 * @throws IOException
	 */
	protected void setErrTipMsg(String pMsg, HttpServletResponse response)
			throws IOException {
		Dto outDto = new BaseDto(CTConstants.FALSE, pMsg);
		write(outDto.toJson(), response);
	}

	/**
	 * 直接输出.
	 * 
	 * @param contentType
	 *            内容的类型.html,text,xml的值见后，json为"text/x-json;charset=UTF-8"
	 */
	protected void render(String text, String contentType) {
		HttpServletResponse response = ServletActionContext.getResponse();
		try {
			response.setContentType(contentType + ";charset="
					+ CTConstants.SYS_PAGE_ENCODE);
			response.getWriter().write(text);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 直接输出纯字符串.
	 */
	protected void renderText(String text) {
		render(text, "text/plain");
	}

	/**
	 * 直接输出纯HTML.
	 */
	protected void renderHtml(String text) {
		render(text, "text/html");
	}

	/**
	 * 直接输出纯XML.
	 */
	protected void renderXML(String text) {
		render(text, "text/xml");
	}
	
	/**
	 * 判断字符串对象是否为空值，如果为空值则返回 true 反之则false。
	 * 
	 * @param str
	 *            字符串对象
	 * @return 布尔值
	 */
	public static boolean isEmpty(String str) {
		return str == null || "".equals(str);
	}

	/**
	 * @see #isEmpty(String)刚好与之相反
	 * @param str
	 *            字符串对象
	 * @return 布尔值
	 */
	public static boolean isNotEmpty(String str) {
		return !isEmpty(str);
	}
	
	
	/**
	 * 转换分页参数
	 * @param dto
	 * @return
	 */
	protected Dto getPageDto(Dto dto){
		/**********************分页开始*************************/
		Integer offset = dto.getAsInteger("pager.offset");
		if (offset != null && offset !=0) {
			pageNo = offset / pageSize;
		    start = (pageNo * pageSize);
		}else{
			start = 0;
		}
		dto.put("start",start);
		dto.put("limit",pageSize);
		/**********************分页结束*************************/
		return dto;
	}
	
	/**
	 * 转换分页参数
	 * @param dto
	 * @return
	 */
	protected Dto getPageDto2(Dto dto){
		/**********************分页开始*************************/
		Integer offset = dto.getAsInteger("pager.offset");
		if (offset != null && offset !=0) {
			pageNo = offset / dto.getAsInteger("page_size");
		    start = (pageNo * dto.getAsInteger("page_size"));
		}else{
			start = 0;
		}
		dto.put("start",start);
		dto.put("limit",dto.getAsInteger("page_size"));
		/**********************分页结束*************************/
		return dto;
	}
	
	/**
	 * 获取分页对象
	 * @param dto
	 * @return
	 */
	protected PageModel getPageModel(List<Dto> dList,int start,int totalCount){
		PageModel pager = new PageModel();
		pager.setDatas(dList);
		pager.setPageNo((start/CTConstants.PAGER_SIZE)+1);
		pager.setPageSize(CTConstants.PAGER_SIZE);
		pager.setCount(totalCount);
		System.out.println("信息集合大小:" + dList.size());
		return pager;
	}
	
	/**
	 * 获取分页对象
	 * @param dto
	 * @return
	 */
	protected PageModel getPageModel(List<Dto> dList,int start,int totalCount,int pageSize){
		PageModel pager = new PageModel();
		pager.setDatas(dList);
		pager.setPageNo((start/pageSize)+1);
		pager.setPageSize(pageSize);
		pager.setCount(totalCount);
		System.out.println("信息集合大小:" + dList.size());
		return pager;
	}
}
